<template>
  <el-dialog v-model="visible" :title="`路由配置 - ${currentRole?.FName || ''}`" width="50%" destroy-on-close>
    <!-- 树的固定高度容器，内部滚动 -->
    <div class="tree-container">
      <el-tree
        ref="treeRef"
        :data="routeTree"
        show-checkbox
        node-key="FId"
        :props="treeProps"
        :default-checked-keys="checkedKeys"
        :default-expanded-keys="expandedKeys"
        :highlight-current="false"
        check-strictly
      />
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage, ElTree } from "element-plus";
import { getRoleRoutesApi, updateRoleRoutesApi } from "@/api/modules/route";

const visible = ref(false);
const treeRef = ref<InstanceType<typeof ElTree>>();
const currentRole = ref<any>(null);
const routeList = ref<any[]>([]); // 原始路由列表数据
const checkedKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]); // 存储要默认展开的节点keys

const treeProps = {
  label: "FTitle",
  children: "children"
};

// 计算属性：将扁平数据转换为树形结构
const routeTree = computed(() => {
  const list = routeList.value;
  if (!list || list.length === 0) return [];

  // 创建映射表
  const map = new Map<string, any>();
  list.forEach(item => map.set(item.FId, { ...item, children: [] }));

  // 构建树形结构
  const tree: any[] = [];
  list.forEach(item => {
    const node = map.get(item.FId);
    if (item.FParentId === "0" || !map.has(item.FParentId)) {
      tree.push(node);
    } else {
      const parent = map.get(item.FParentId);
      parent.children.push(node);
    }
  });
  return tree;
});

// 打开弹窗
const open = async (role: any) => {
  currentRole.value = role;
  try {
    // 获取角色路由数据
    const { data } = await getRoleRoutesApi({ FRoleId: role.FId });

    routeList.value = data;
    // 提取选中 keys
    checkedKeys.value = data.filter(item => item.FHasPermission).map(item => item.FId);
    // 设置默认展开所有有子节点的路由
    expandedKeys.value = data.filter(item => data.some(child => child.FParentId === item.FId)).map(item => item.FId);

    visible.value = true;
  } catch (e) {
    console.error(e);
    ElMessage.error("获取路由数据失败");
  }
};

// 提交保存
const handleSubmit = async () => {
  try {
    const checked = (treeRef.value?.getCheckedKeys(false) as string[]) || [];
    const halfChecked = (treeRef.value?.getHalfCheckedKeys() as string[]) || [];
    const allSelected = [...checked, ...halfChecked];

    await updateRoleRoutesApi({
      FRoleId: currentRole.value.FId,
      FRouteIds: allSelected
    });

    ElMessage.success("路由配置保存成功");
    visible.value = false;
  } catch (e) {
    console.error(e);
    ElMessage.error("保存失败");
  }
};

defineExpose({ open });
</script>

<style scoped>
.tree-container {
  max-height: 400px;
  padding-right: 8px;
  overflow-y: auto;
}
</style>
